﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlogDemo.Api.Infrastructure.Extensions
{
    public static class ExceptionHandlerExt
    {
        public static void  UseCustomExceptionHandler(this IApplicationBuilder app,ILoggerFactory loggerFactory)
        {
            app.UseExceptionHandler(builder =>
            {
                builder.Run(async ctx =>
                {
                    ctx.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    ctx.Response.ContentType = "application/json";
                    var ex = ctx.Features.Get<IExceptionHandlerFeature>();
                    if (ex!=null)
                    {
                        var logger = loggerFactory.CreateLogger(typeof(ExceptionHandlerExt));
                        logger.LogError(ex.Error,ex.Error.Message);
                    }
                    await ctx.Response.WriteAsync(ex?.Error?.Message??"Error occured!");
                });
            });
        }
    }
}
